跳到主要内容

3-生命周期

Create by fall on:2021-11-14 Recently revised in:2022-01-19

ShouldComopnentUpdate

覆盖生命周期方法 shouldComponentUpdate 来进行提速。该方法会在重新渲染前被触发。其默认实现总是返回 true,让 React 执行更新:

// React 执行更新:
shouldComponentUpdate(){
return true
}
// 如果你知道什么时候要 React 不需要执行更新,可以通过返回 false
shouldComponentUpdate(){
return false
}

如果一个父组件是不需要更新的,那么子组件也不需要更新,

是否渲染也就是三种情况

  • shouldComponentUpdate 为 true 会触发子组件的更改
  • shouldComponentUpdate 为 true 且 vDOM 不同则更改,相同,则不更改
  • shouldComponentUpdate 为 false,就不会触发更改
// 如果只是在某些特定的值改变才触发更新的话,可以使用 shouldComponentUpdate 进行判断是否需要更新
class CounterButton extends React.component{
constructor(props){
super(props)
this.state = {count:1}
}
shouldComponentUpdate(nextProps,nextState){
if(this.props.color !== nextPorps.color){
return true
}
if(this.state.count !== nextState.count){
return true
}
return false
}
render(){
return(
<button color="red">颜色</button>
)
}
}

Portals

把子节点渲染到父组件以外的 DOM 节点的方案

比如说下面是 html 上挂载的节点

<html>
<body>
<div id="app-root"> </div>
<div id="modal-root"> </div>
</body>
</html>

对节点进行操作

const appRoot = document.getElementById('app-root')
const modalRoot = document.getElementById("modal-root")
// 在 DOM 上挂载 Portal 节点
class Modal extends React.Component{
constructor(props){
super(props)
this.el = document.createElement('div')
}
componentDidMount(){
modalRoot.appendChild(this.el)
}
componentWillUnmount(){
modalRoot.removeChild(this.el)
}
render(){
return ReactDOM.createPortal(
this.props.children,
this.el
)
}
}
class Parent extends React.Component{
constructor(props){
super(props)
this.state = {clicks:0}
this.handleClick = this.handleClick.bind(this)
}
handleClick(){
this.setState(state=>{
clicks:state.clicks + 1
})
}
render(){
return (
<div onClick={this.handleClick}>
<p>Number of Clicks {this.state.clicks}</p>
<Modal>
<Clild/>
</Modal>
</div>
)
}
}
function Clild(){
return(
<div className="modal">
<button>点,来点</button>
</div>
)
}
ReactDOM.render(<Parent/>,appRoot)